package com.njlime.sys.controller;


import com.alibaba.fastjson.JSONObject;
import com.njlime.core.exception.ExceptionState;
import com.njlime.core.utils.DateUtil;
import com.njlime.sys.util.ImageUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * 控制器-资源图片信息
 *
 */
@Controller
public class ImageUploadController {

    private static final Logger logger = Logger.getLogger("ImageUploadController");
    public static final String HTDOCS = "/htdocs/images/";
    private static long maxSize = 10 * 1024 * 1024;

    private static HashMap<String, String> extMap = new HashMap<String, String>();
    private static final String IMAGE = "image";
    private static String url;
    /** 要保存的文件名 */
    protected static String prefix;
    /** 服务器本地保存路径 */
    protected static String picPath;
    /** 后缀 */
    protected static String suffix;

    @RequestMapping(value = "/uploadOneImageFile", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String  uploadOneImageFile(MultipartHttpServletRequest request, HttpServletResponse resp) {
        Logger.getLogger(this.getClass()).info(new Date().getTime() + "开始执行上传");
        /** 定义字符串类型变量imgurl */
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",ExceptionState.BUSINESS_EXCEPTION);
        String imgurl ;
        List<MultipartFile> muFiles = request.getFiles("uploadImg");

        /** 如果获取的file不为null并且size大于0 */
        if (null != muFiles && !muFiles.isEmpty()) {
            /** 如果获取的file的size等于1 */
            if (muFiles.size() == 1) {
                // 关闭client
                int c = checkFile(muFiles.get(0));
                if (c == 1) {
                    /** 调用图片上传方法 */
                    imgurl = uploadFile(muFiles.get(0), request);
                    if(imgurl==null){
                        imgurl="-1";
                        jsonObject.put("code",ExceptionState.BUSINESS_EXCEPTION);
                        jsonObject.put("message","上传失败");
                    }else{
                        jsonObject.put("code", ExceptionState.SUCCESS);
                        JSONObject resultList = new JSONObject();
                        resultList.put("url",imgurl);
                        jsonObject.put("resultList",resultList);
                    }
                }else if(c == -2){
                    jsonObject.put("code",ExceptionState.BUSINESS_EXCEPTION);
                    jsonObject.put("message","文件过大");
                }
            }
        }
        return jsonObject.toJSONString();
    }


    /**
     * 按照大、中、小、原图处理图片
     *
     * @param muFile
     * @return Map集合，其中有4个值，oldimg是原图，0：小图、1：中图、2：大图
     */
    public static String uploadForABCSize(MultipartFile muFile, HttpServletRequest request) {
        Map<String, String> imgMap = new HashMap<String, String>();
        if (muFile != null && muFile.getSize() != 0) {
            // 获取项目url
            url = getHttpAndPort(request);
            // 获取上传文件的保存名称、服务器本地保存路径、后缀，拼接成文件地址
            String fileNamess = getPicNamePathSuffix();
            fileNamess = fileNamess.substring(0,fileNamess.lastIndexOf(".")+1) + muFile.getOriginalFilename().substring(muFile.getOriginalFilename().lastIndexOf(".")+1).toLowerCase();
            File file = new File(fileNamess);

            try {
                muFile.transferTo(file);
                //裁剪
                logger.info("开始裁剪");
                String dataXStr = request.getParameter("dataX");
                if(dataXStr==null || "".equals(dataXStr.trim())){
                    dataXStr = "0";
                }
                String dataYStr = request.getParameter("dataY");
                if(dataYStr==null || "".equals(dataYStr.trim())){
                    dataYStr = "0";
                }
                String dataWidthStr = request.getParameter("dataWidth");
                String dataHeightStr = request.getParameter("dataHeight");
                if(dataHeightStr==null || "".equals(dataHeightStr.trim()) || dataWidthStr==null || "".equals(dataWidthStr.trim())){
                    BufferedImage bi = ImageIO.read(new FileInputStream(file));
                    dataHeightStr = bi.getHeight() + "";
                    dataWidthStr = bi.getWidth() + "";
                }
                Integer dataX = Integer.valueOf(dataXStr);
                Integer dataY = Integer.valueOf(dataYStr);
                Integer dataHeight = Integer.valueOf(dataHeightStr);
                Integer dataWidth = Integer.valueOf(dataWidthStr);
                if (dataX != null && dataY != null && dataHeight != null && dataWidth != null) {
                    ImageUtil.cutPic(file.getPath(), file.getPath(), dataX, dataY, dataWidth, dataHeight);
                }
            }catch (Exception e){
                //e.printStackTrace();
                logger.info("图片裁剪出错："+e.getMessage());
            }
            fileNamess= url+fileNamess.replace(HTDOCS, "/serverimage/");
            return fileNamess;
        } else {
            return null;
        }
    }
    private static String getHttpAndPort(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
    }
    public static String getPicNamePathSuffix() {
        // 根据系统时间生成上传后保存的文件名
        long now = System.currentTimeMillis();
        prefix = String.valueOf(now);

        picPath =  HTDOCS + DateUtil.dateFormat(new Date(),"yyyyMMdd") + "/";

        // 根据真实路径创建目录文件
        File picSaveFile = new File(picPath);
        if (!picSaveFile.exists()) {
            try {
                picSaveFile.mkdirs();
            } catch (Exception e) {
                logger.error(e.getLocalizedMessage(), e);
            }
        }
        // 文件的后缀
        suffix = ".jpg";
        return picPath + prefix + suffix;
    }

    /**
     * 验证上传的资源
     *
     * @param muFile
     * @return int
     */
    private int checkFile(MultipartFile muFile) {
        /** 定义一个Int类型的变量 */
        int result = 0;
        /** 获取文件上传设置类信息 */
        /** 定义suffixArray数组，并赋值 */
        String[] suffixArray = "jpg,jpeg,png,gif,bmp,ico".split(",");
        /** 如果传入参数muFile不为null并且size大于0 */
        if (null != muFile && muFile.getSize() > 0) {
            /** 如果木File的size小于文件上传设置类的最大size */
            if (muFile.getSize() < 2097152) {
                /** 获取muFile的名称并赋值给fileName */
                String filename = muFile.getOriginalFilename();
                /** 定义变量sufix */
                String sufix = null;
                try {
                    /** 为sufix赋值 */
                    sufix = filename.substring(filename.lastIndexOf(".") + 1);
                } catch (Exception e) {
                    logger.error("上传的文件没有后缀名!", e);
                    result = -3;
                }

                for (int i = 0; i < suffixArray.length; i++) {
                    if (sufix.equalsIgnoreCase(suffixArray[i])) {
                        result = 1;
                        break;
                    } else {
                        /** 禁止上传的后缀 */
                        result = -3;
                    }
                }

            } else {
                /** 文件过大 */
                result = -2;
            }
        } else {
            /** 没有上传文件 */
            result = -1;
        }
        return result;
    }

    /**
     * 图片上传，返回key值列表
     *
     * @param muFile
     *            图片
     * @param request
     *            HttpServletRequest
     * @return Map 返回中 key值{0,1,2,oldimg} 0小图 1中图 2大图 oldimg 原图
     */
    public static synchronized String uploadFile(MultipartFile muFile, HttpServletRequest request) {
        Map<String, String> map = null;

        if (muFile != null && muFile.getSize() != 0) {
            // 检查上传的图片的大小和扩展名
            if (!checkFileForSpringUpload(muFile)) {
                throw new RuntimeException("上传" + muFile.getOriginalFilename() + "失败");
            }

            // 本地服务器保存
            return   uploadForABCSize(muFile,request);

        }
        return null;
    }
    private static boolean checkFileForSpringUpload(MultipartFile muFile) {
        boolean bool = true;
        // 检查文件大小
        if (muFile.getSize() > maxSize) {
            logger.error("=============>上传" + muFile.getOriginalFilename() + "文件大小超过限制");
            bool = false;
        }
        String fileName = muFile.getOriginalFilename();
        // 检查扩展名
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (!Arrays.<String> asList(extMap.get(IMAGE).split(",")).contains(fileExt)) {
            logger.error("上传文件" + muFile.getOriginalFilename() + "扩展名是不允许的扩展名。\n只允许" + extMap.get(IMAGE) + "格式。");
            bool = false;
        }
        return bool;
    }
    static {
        extMap.put(IMAGE, "gif,jpg,jpeg,png,bmp,ico");
    }


}
